package com.gsafety.wellsfort.service.security.impl;

import com.gsafety.wellsfort.common.context.LoginContext;
import com.gsafety.wellsfort.common.context.LoginContextUtil;
import com.gsafety.wellsfort.common.util.ApiResponse;
import com.gsafety.wellsfort.common.util.MapUtils;
import com.gsafety.wellsfort.common.util.ResultCode;
import com.gsafety.wellsfort.dao.organization.SchoolDAO;
import com.gsafety.wellsfort.dao.security.AdminDAO;
import com.gsafety.wellsfort.dao.security.AdminRoleRelDAO;
import com.gsafety.wellsfort.dao.security.RoleDAO;
import com.gsafety.wellsfort.dao.security.UserLoginDAO;
import com.gsafety.wellsfort.domain.dto.secuirty.AdminDto;
import com.gsafety.wellsfort.domain.model.organization.School;
import com.gsafety.wellsfort.domain.model.security.Admin;
import com.gsafety.wellsfort.domain.model.security.AdminRoleRel;
import com.gsafety.wellsfort.domain.model.security.Role;
import com.gsafety.wellsfort.domain.model.security.UserLogin;
import com.gsafety.wellsfort.domain.vo.AdminQueryVO;
import com.gsafety.wellsfort.domain.vo.AdminResultVO;
import com.gsafety.wellsfort.service.security.IAdminService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class AdminServiceImpl implements IAdminService {
    @Autowired
    private AdminDAO adminDAO;

    @Autowired
    private UserLoginDAO userLoginDAO;

    @Autowired
    private AdminRoleRelDAO adminRoleRelDAO;

    @Autowired
    private RoleDAO roleDAO;

    @Autowired
    private SchoolDAO schoolDAO;


    @Override
    public Admin getByLoginId(Integer loginId) {
        Admin admin = adminDAO.getByLoginId(loginId);
        if (admin != null) {
            List<AdminRoleRel> list = adminRoleRelDAO.selectByAdminId(admin.getId());
            if (list != null && list.size() > 0) {
                admin.setRoleId(list.get(0).getRoleId());
            }
        }
        return admin;
    }

    @Override
    public ApiResponse add(AdminDto adminDto) {
        UserLogin uLogin = userLoginDAO.selectByAccount(adminDto.getAccount());
        if (uLogin != null) {
            return ApiResponse.error(ResultCode.ACCOUNT_HAS_EXIST);
        }
        //插入管理员记录
        Admin admin = convertDto2Do(adminDto);
        //插入登录表记录
        UserLogin userLogin = UserLogin.builder().account(adminDto.getAccount())
                .password(DigestUtils.md5Hex(adminDto.getPassword())).
                        originalPassword(adminDto.getPassword()).type((byte) 2).
                        status(admin.getStatus()).created(admin.getCreated()).modified(admin.getCreated()).
                        creator(LoginContextUtil.getUserName()).
                        operator(LoginContextUtil.getUserName()).
                        build();
        Integer insert = userLoginDAO.insertSelective(userLogin);
        if (insert > 0) {
            admin.setLoginId(userLogin.getId());
            int inserted = adminDAO.insertSelective(admin);
            if (inserted > 0) {
                //管理员关联角色
                AdminRoleRel adminRoleRel = new AdminRoleRel();
                adminRoleRel.setAdminId(admin.getId());
                adminRoleRel.setRoleId(adminDto.getRoleId());
                adminRoleRel.setStatus(adminDto.getStatus().byteValue());
                adminRoleRel.setCreated(admin.getCreated());
                adminRoleRel.setModified(admin.getCreated());
                adminRoleRel.setCreator(LoginContextUtil.getUserName());
                adminRoleRel.setOperator(LoginContextUtil.getUserName());
                if (adminRoleRelDAO.insertSelective(adminRoleRel) > 0) {
                    return ApiResponse.success();
                }
            }
        }
        return ApiResponse.error();
    }

    @Override
    public boolean update(AdminDto adminDto) {
        Admin admin = convertDto2Do(adminDto);
        admin.setCreator(null);
        admin.setCreated(null);
        admin.setModified(new Date());
        admin.setOperator(LoginContextUtil.getUserName());
        if (adminDAO.updateByPrimaryKeySelective(admin) > 0) {
            Admin newAdmin = adminDAO.selectByPrimaryKey(adminDto.getId());
            if (StringUtils.isNotEmpty(adminDto.getAccount()) || StringUtils.isNotEmpty(adminDto.getPassword())) {
                UserLogin userLogin = UserLogin.builder().id(newAdmin.getLoginId()).account(adminDto.getAccount()).
                        password(adminDto.getPassword() == null ? null : DigestUtils.md5Hex(adminDto.getPassword())).originalPassword(adminDto.getPassword()).
                        status(adminDto.getStatus() == null ? 0 : adminDto.getStatus().byteValue()).modified(new Date()).operator(LoginContextUtil.getUserName()).build();
                userLoginDAO.updateByPrimaryKeySelective(userLogin);
            }
            //管理员关联角色更新(先删除,再添加)
            adminRoleRelDAO.deleteByAdminId(admin.getId());
            if (adminDto.getRoleId() != null) {
                AdminRoleRel adminRoleRel = new AdminRoleRel();
                adminRoleRel.setAdminId(admin.getId());
                adminRoleRel.setRoleId(adminDto.getRoleId());
                adminRoleRel.setStatus(adminDto.getStatus().byteValue());
                adminRoleRel.setCreated(new Date());
                adminRoleRel.setModified(new Date());
                adminRoleRel.setOperator(LoginContextUtil.getUserName());
                adminRoleRelDAO.insertSelective(adminRoleRel);
            }
        }
        return true;
    }

    @Override
    public boolean delete(Integer adminId) {
        //删除管理员信息
        Admin admin = adminDAO.selectByPrimaryKey(adminId);
        if (admin != null) {
            adminDAO.deleteByPrimaryKey(adminId);
            //删除登录信息
            userLoginDAO.deleteByPrimaryKey(admin.getLoginId());
            return true;
        }
        return false;
    }

    @Override
    public ApiResponse<List<Admin>> pageQuery(AdminQueryVO query) {
        Map<String, Object> param = MapUtils.buildQueryParam(query);
        Integer count = adminDAO.countAdmin(param);
        List<Admin> list = adminDAO.pageQuery(param);
        if (list != null && list.size() > 0) {
            for (Admin admin : list) {
                School school = schoolDAO.selectByPrimaryKey(admin.getSchoolId());
                admin.setSchoolName(school.getName());
                List<AdminRoleRel> adminRoleRelList = adminRoleRelDAO.selectByAdminId(admin.getId());
                if (adminRoleRelList != null && adminRoleRelList.size() > 0) {
                    admin.setRoleId(adminRoleRelList.get(0).getRoleId());
                }
            }
        }
        return ApiResponse.success(list, count);
    }

    /**
     * @param adminDto
     * @return
     */
    private Admin convertDto2Do(AdminDto adminDto) {
        Admin admin = new Admin();
        Date date = new Date();
        BeanUtils.copyProperties(adminDto, admin);
        admin.setType(adminDto.getType().byteValue());
        admin.setStatus(adminDto.getStatus().byteValue());
        admin.setCreated(date);
        admin.setModified(date);
        admin.setCreator(LoginContextUtil.getUserName());
        admin.setOperator(LoginContextUtil.getUserName());
        return admin;
    }


    /**
     * @param
     * @return
     */
    @Override
    public ApiResponse<List<AdminResultVO>> convertDo2VO(ApiResponse<List<Admin>> apiResponse) {
        if (apiResponse != null) {
            if (apiResponse.getCode() == 0) {
                List<Admin> list = apiResponse.getData();
                List<AdminResultVO> resultList = new ArrayList<>();
                if (list != null && list.size() > 0) {
                    for (Admin admin : list) {
                        AdminResultVO adminResultVO = new AdminResultVO();
                        BeanUtils.copyProperties(admin, adminResultVO);
                        UserLogin userLogin = userLoginDAO.selectByPrimaryKey(admin.getLoginId());
                        adminResultVO.setAccount(userLogin.getAccount());
                        List<AdminRoleRel> adminRoleRelList = adminRoleRelDAO.selectByAdminId(admin.getId());
                        if (adminRoleRelList != null && adminRoleRelList.size() > 0) {
                            Integer roleId = adminRoleRelList.get(0).getRoleId();
                            adminResultVO.setRoleId(roleId);
                            Role role = roleDAO.selectByPrimaryKey(roleId);
                            adminResultVO.setRoleName(role.getName());
                        }
                        resultList.add(adminResultVO);
                    }
                }
                return ApiResponse.success(resultList, apiResponse.getCount());
            }
            return ApiResponse.error(ResultCode.ERROR.getCode(), apiResponse.getMsg());
        }
        return ApiResponse.error();
    }

    @Override
    public Admin get(Integer id) {
        return adminDAO.selectByPrimaryKey(id);
    }
}
